package org.qydjk.console.controller.common;

import org.apache.commons.fileupload.FileUploadException;
import org.qydjk.common.constant.CommonConstant;
import org.qydjk.common.constant.RedisConstant;
import org.qydjk.common.controller.BaseController;
import org.qydjk.common.ueditor.ActionEnter;
import org.qydjk.common.ueditor.define.ActionMap;
import org.qydjk.common.ueditor.define.BaseState;
import org.qydjk.common.ueditor.define.MultiState;
import org.qydjk.common.util.FileUtil;
import org.qydjk.common.util.RedisTemplateUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.util.ThumbnailatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping("/file")
public class FileController extends BaseController {
    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @RequestMapping("/upload.do")
    @ResponseBody
    public String upload() throws IOException, FileUploadException {
        if(CommonConstant.COMMON_FILE_WAY == 0){
            //传到本地
            return ueditorUpload(request,session);
        }else if(CommonConstant.COMMON_FILE_WAY == 1){
            //阿里云

        }
        return null;
    }


    /**
     * 百度编辑器上传处理
     * @param request
     * @param session
     * @return
     */
    private String ueditorUpload(HttpServletRequest request,HttpSession session){
        try {
            request.setCharacterEncoding( "utf-8" );
            String rootPath = session.getServletContext().getRealPath( "/static/ueditor1.4.3.3/jsp" );
            Object res = new ActionEnter(request, rootPath, CommonConstant.COMMON_FILE_PATH).exec();
            String cls = res.getClass().getName();
            if(cls.equals(String.class.getName())){
                return res.toString();
            }else if(cls.equals(BaseState.class.getName())){
                BaseState state = (BaseState) res;
                String compressType = request.getParameter("compress");
                if(StringUtil.isEmptyOrNull(compressType)){
                    compressType = "0";
                }
                String action = request.getParameter("action");
                if(!StringUtil.isEmptyOrNull(action) && (action.equals(ActionMap.UPLOAD_IMAGE_STRING) || action.equals(ActionMap.UPLOAD_SCRAWL_STRING) || action.equals(ActionMap.CATCH_IMAGE_STRING)) && !StringUtil.isEmptyOrNull(compressType)){
                    //图片进行压缩
                    imageThumbnai(state,compressType);
                }
                return state.toJSONString();
            }else if(cls.equals(MultiState.class.getName())){
                MultiState state = (MultiState) res;
                return state.toJSONString();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 图片需要压缩
     * @param state
     * @param compressType 指定压缩类型，不同地方可能压缩类型不同
     */
    private void imageThumbnai(BaseState state,String compressType){
        String originPath = CommonConstant.COMMON_FILE_PATH + state.getUrl();
        String thumbnaiPath = CommonConstant.COMMON_FILE_PATH + state.getUrl().replace(CommonConstant.COMMON_FILE_ORIGIN_FOLDER,CommonConstant.COMMON_FILE_THUMBNAI_FOLDER);
        String folderStr = thumbnaiPath.substring(0, thumbnaiPath.lastIndexOf("/"));
        File folder = new File(folderStr);
        if(!folder.exists()){
            folder.mkdir();
        }
        String wh = (String) redisTemplateUtil.getWithByte(RedisConstant.ImageCompressTypeKey + compressType);
        if(!StringUtil.isEmptyOrNull(wh)){
            String[] whArr = wh.split(",");
            ThumbnailatorUtils.ImgThumb(originPath,thumbnaiPath,Integer.parseInt(whArr[0]),Integer.parseInt(whArr[1]));
        }else{
            //没有配置压缩，就把原图拷贝过来
            FileUtil.copyFile(originPath,thumbnaiPath);
        }
    }
}
